/*
 * @(#) LoginController
 *
 * <br> Copyright:  Copyright (c) 2017
 * <br> @author caijinhuang
 * <br> 2017-12-18 16:01:11
 */

package com.sunsharing.sharemeeting.web.controll.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunsharing.sharemeeting.entity.ResponseModel;
import com.sunsharing.sharemeeting.entity.User;
import com.sunsharing.sharemeeting.service.api.UserService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginController {
    @Resource
    private UserService userService;
    /**
     * 登陆：账号登陆
     * @param params ：json对象
     *  参数：username （用户名）
     *      password （密码）
     * @return
     */

    @RequestMapping(value = "/checkLogin.do",method = RequestMethod.POST)
    @ResponseBody
    public String checkLogin(@RequestBody JSONObject params,HttpSession session)
        throws UnsupportedEncodingException, NoSuchAlgorithmException {
        User user = userService.checkLogin(params.getString("username"),params.getString("password"));
        ResponseModel responseModel = null;
        if (user != null) {
            responseModel = new ResponseModel(true,user.getNickname() + ",欢迎您的登陆",null);
            session.setAttribute("user",user);
            return JSON.toJSONString(responseModel);
        } else {
            responseModel = new ResponseModel(false,"对不起,账号或密码错误，请重新登陆",null);
            return JSON.toJSONString(responseModel);
        }
    }


    /**
     * 登出：退出登陆
     * @return
     */
    @RequestMapping(value = "/loginOut.do",method = RequestMethod.POST)
    @ResponseBody
    public String loginOut(HttpSession session) {
        session.removeAttribute("user");
        ResponseModel responseModel = new ResponseModel(true, "退出登陆", null);
        return JSON.toJSONString(responseModel);
    }



    /**
     * 首页：获取用户信息
     * @return
     */
    @RequestMapping(value = "/getMeeting.do",method = RequestMethod.POST)
    @ResponseBody
    public String getMeeting(HttpSession session) {
        User user = (User)session.getAttribute("user");
        User result = new User();
        result.setUsername(user.getUsername());
        result.setDepartmentName(user.getDepartmentName());
        result.setEmail(user.getEmail());
        result.setNickname(user.getNickname());
        result.setUserId(user.getUserId());
        result.setRoleName(user.getRoleName());
        ResponseModel responseModel = new ResponseModel(true,"已登陆",result);
        return JSON.toJSONString(responseModel);
    }

}
